package com.example.android.test.project2;

import com.example.android.javascript.project2.JavscriptInterface;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class ResultsPageActivity extends Activity {
    public static final String DATANAME = "name";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_results_page);
        
        String firstName= "";
        String lastName="";
        Intent intent = getIntent();
        if(intent!=null){
          firstName = intent.getStringExtra(MainActivity.FIRSTNAME);
          lastName = intent.getStringExtra(MainActivity.LASTNAME);
        }
      
        // Setting up the webview
        WebView myWebView = (WebView) findViewById(R.id.results_page);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);       
        myWebView.addJavascriptInterface(new JavscriptInterface(this), "Android");
        
        //Adding value to shared preferences
        //Create or retrieve the activity preference object
        SharedPreferences activityPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        //Retrieve editor to modify the shared preferences
        SharedPreferences.Editor editor = activityPreferences.edit();
        //Store value
        editor.putString(DATANAME, "Walt Whipman");
        //Commit changes
        editor.apply();

        //setting up web client
        myWebView.setWebViewClient(new WebViewClient() {
          //Progress at the center of the screen
          ProgressDialog  dialog = ProgressDialog.show(ResultsPageActivity.this, "","Please wait loading...");
          
          @Override
          public void onReceivedError(WebView view, int errorCode,
              String description, String failingUrl) {
            // Handle the error
          }

          @Override
          public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);          
            return true;
          }
          
          @Override
          public void onPageFinished(WebView view, String url)  {
            dialog.dismiss();
          }
                
        });

        myWebView.loadUrl("http://www.treadstoneweb.com/serviceResult.php?firstName=" + firstName + "&lastName=" + lastName);        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_results_page, menu);
        return true;
    }
}
